﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Lib.Helper;
using MSIACCSL2.AppParamServices;
using MSIACCSL2.Command;
using MSIACCSL2.GroupServices;
using MSIACCSL2.ItemServices;
using MSIACCSL2.SubGroupServices;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using System.ComponentModel;
using System.Linq;

namespace MSIACCSL2.ViewModels
{
    public class KartuStokViewModel : ViewModelBase
    {
        private GroupServices.GroupServicesClient groupClient;
        private WarehouseServices.WarehouseServicesClient warehouseClient;
        private SubGroupServices.SubGroupServiceClient subgroupClient;
        private ItemServices.ItemServicesClient itemClient;
        private ObservableCollection<ItemDTO> _Items;
        private ObservableCollection<SubGroupDTO> _SubGroups;
        private ObservableCollection<WarehouseDTO> _warehouses;
        private ObservableCollection<GroupDTO> _Groups;
        private string _Keterangan;
        private DateTime? _Periode;
        private string _KodeMasuk;
        private string _NoLog;
        private string _Pallet;
        private Decimal _Panjang1;
        private Decimal _Panjang2;
        private Decimal _Lebar1;
        private Decimal _Tinggi1;
        private Decimal _Lebar2;
        private Decimal _Tinggi2;
        private Decimal _Hpp;
        private int _NoBundle;
        private Decimal _Amount;
        private WarehouseDTO _Warehouse;
        private AppParamServices.AppParamServicesClient paramClient;
        private string ReportUrl;
        private bool _IsDetail;
        private bool _IsSummary;

        public KartuStokViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                groupClient = new GroupServicesClient();
                warehouseClient = new WarehouseServicesClient();
                subgroupClient = new SubGroupServiceClient();
                itemClient = new ItemServicesClient();
                paramClient = new AppParamServicesClient();
                ShowCommand = new DelegateCommand(Show, CanshowCommand);
                GetServerUrl();
                PrepareData();
                
            }
        }


        public void PrepareData()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                                                          {
                                                              GetWarehouseList();
                                                              GetSubgroupList();
                                                              GetItemList();
                                                              GetGroupList();
                                                              Periode = DateTime.Now.Date;
                                                          });
                                                             

        }




        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _warehouses; }
            set
            {
                if (Warehouses == value) return;
                _warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }


        public ObservableCollection<GroupDTO> Groups
        {
            get { return _Groups; }
            set
            {
                if (Groups == value) return;
                _Groups = value;
                FirePropertyChanged("Groups");
            }
        }



        public ObservableCollection<SubGroupDTO> SubGroups
        {
            get { return _SubGroups; }
            set
            {
                if (SubGroups == value) return;
                _SubGroups = value;
                FirePropertyChanged("SubGroups");
            }
        }

        public ObservableCollection<ItemDTO> Items
        {
            get { return _Items; }
            set
            {
                if (Items == value) return;
                _Items = value;
                FirePropertyChanged("Items");
            }
        }

        public DateTime? Periode
        {
            get { return _Periode; }
            set
            {
                if (Periode == value) return;
                _Periode = value;
                FirePropertyChanged("Periode");
            }
        }

        public string NoLog
        {
            get { return _NoLog; }
            set
            {
                if (NoLog == value) return;
                _NoLog = value;
                FirePropertyChanged("NoLog");
            }
        }



        public string Pallet
        {
            get { return _Pallet; }
            set
            {
                if (Pallet == value) return;
                _Pallet = value;
                FirePropertyChanged("Pallet");
            }
        }

        public string KodeMasuk
        {
            get { return _KodeMasuk; }
            set
            {
                if (KodeMasuk == value) return;
                _KodeMasuk = value;
                FirePropertyChanged("KodeMasuk");
            }
        }


        public Decimal Panjang1
        {
            get { return _Panjang1; }
            set
            {
                if (Panjang1 == value) return;
                _Panjang1 = value;
                FirePropertyChanged("Panjang1");
            }
        }


        public Decimal Panjang2
        {
            get { return _Panjang2; }
            set
            {
                if (Panjang2 == value) return;
                _Panjang2 = value;
                FirePropertyChanged("Panjang2");
            }
        }


        public Decimal Lebar1
        {
            get { return _Lebar1; }
            set
            {
                if (Lebar1 == value) return;
                _Lebar1 = value;
                FirePropertyChanged("Lebar1");
            }
        }


        public Decimal Lebar2
        {
            get { return _Lebar2; }
            set
            {
                if (Lebar2 == value) return;
                _Lebar2 = value;
                FirePropertyChanged("Lebar2");
            }
        }

        public Decimal Tinggi1
        {
            get { return _Tinggi1; }
            set
            {
                if (Tinggi1 == value) return;
                _Tinggi1 = value;
                FirePropertyChanged("Tinggi1");
            }
        }

        public Decimal Tinggi2
        {
            get { return _Tinggi2; }
            set
            {
                if (Tinggi2 == value) return;
                _Tinggi2 = value;
                FirePropertyChanged("Tinggi2");
            }
        }

        public Decimal Hpp
        {
            get { return _Hpp; }
            set
            {
                if (Hpp == value) return;
                _Hpp = value;
                FirePropertyChanged("Hpp");
            }
        }

        public Decimal Amount
        {
            get { return _Amount; }
            set
            {
                if (Amount == value) return;
                _Amount = value;
                FirePropertyChanged("Amount");
            }
        }

        public int NoBundle
        {
            get { return _NoBundle; }
            set
            {
                if (NoBundle == value) return;
                _NoBundle = value;
                FirePropertyChanged("NoBundle");
            }
        }

        public string Keterangan
        {
            get { return _Keterangan; }
            set
            {
                if (Keterangan == value) return;
                _Keterangan = value;
                FirePropertyChanged("Keterangan");
            }
        }

        public WarehouseDTO Warehouse
        {
            get { return _Warehouse; }
            set
            {
                if (Warehouse == value) return;
                _Warehouse = value;
                FirePropertyChanged("Warehouse");
            }
        }


        public bool IsSummary
        {
            get { return _IsSummary; }
            set
            {
                if (IsSummary == value) return;
                _IsSummary = value;
                FirePropertyChanged("IsSummary");
            }
        }


        public bool IsDetail
        {
            get { return _IsDetail; }
            set
            {
                if (IsDetail == value) return;
                _IsDetail = value;
                FirePropertyChanged("IsDetail");
            }
        }


        public ICommand ShowCommand { get; set; }

        public bool CanshowCommand(Object param)
        {
            return true;
        }


        public void GetServerUrl()
        {
            paramClient.GetAppParamListCompleted += new EventHandler<GetAppParamListCompletedEventArgs>(paramClient_GetAppParamListCompleted);
            paramClient.GetAppParamListAsync("ReportUrl");
        }

        void paramClient_GetAppParamListCompleted(object sender, GetAppParamListCompletedEventArgs e)
        {
            paramClient.GetAppParamListCompleted -= new EventHandler<GetAppParamListCompletedEventArgs>(paramClient_GetAppParamListCompleted);
            ReportUrl = e.Result.FirstOrDefault().AppParamValue;
        }
        public void GetWarehouseList()
        {
            warehouseClient.GetAllWarehouseCompleted += new EventHandler<GetAllWarehouseCompletedEventArgs>(warehouseClient_GetAllWarehouseCompleted);
            warehouseClient.GetAllWarehouseAsync();
        }

        void warehouseClient_GetAllWarehouseCompleted(object sender, GetAllWarehouseCompletedEventArgs e)
        {
            warehouseClient.GetAllWarehouseCompleted -= new EventHandler<GetAllWarehouseCompletedEventArgs>(warehouseClient_GetAllWarehouseCompleted);
            Warehouses = e.Result;
            Warehouses.Insert(0,new WarehouseDTO());
        }

        public void GetItemList()
        {
            itemClient.GetAllItemCompleted += new EventHandler<GetAllItemCompletedEventArgs>(itemClient_GetAllItemCompleted);
            itemClient.GetAllItemAsync();
        }

        void itemClient_GetAllItemCompleted(object sender, GetAllItemCompletedEventArgs e)
        {
            itemClient.GetAllItemCompleted -= new EventHandler<GetAllItemCompletedEventArgs>(itemClient_GetAllItemCompleted);
            Items = e.Result;
            Items.Insert(0,new ItemDTO());
        }

        public void GetGroupList()
        {
            groupClient.GetAllCompleted += new EventHandler<GetAllCompletedEventArgs>(groupClient_GetAllCompleted);
            groupClient.GetAllAsync();
        }

        void groupClient_GetAllCompleted(object sender, GetAllCompletedEventArgs e)
        {
            groupClient.GetAllCompleted -= new EventHandler<GetAllCompletedEventArgs>(groupClient_GetAllCompleted);
            Groups = e.Result;
            Groups.Insert(0,new GroupDTO());
        }

        public void GetSubgroupList()
        {
            subgroupClient.GetAllSubGroupCompleted += new EventHandler<GetAllSubGroupCompletedEventArgs>(subgroupClient_GetAllSubGroupCompleted);
            subgroupClient.GetAllSubGroupAsync();
        }

        void subgroupClient_GetAllSubGroupCompleted(object sender, GetAllSubGroupCompletedEventArgs e)
        {
            subgroupClient.GetAllSubGroupCompleted -= new EventHandler<GetAllSubGroupCompletedEventArgs>(subgroupClient_GetAllSubGroupCompleted);
            SubGroups = e.Result;
            SubGroups.Insert(0,new SubGroupDTO());
        }

        public void Show(Object param)
        {
            StringBuilder sb = new StringBuilder();


            if (Warehouse == null || string.IsNullOrEmpty(Warehouse.KodeWarehouse))
            {
                sb.Append("Select * from ( ");
                sb.Append(" SELECT ");
                sb.Append(" i.SerialNumber,b.ItemId,b.ItemName,c.SubGroupId,c.SubGroupName,d.GroupId,d.GroupName,    ");
                sb.Append(" i.NoBundle,i.QtyPack,i.Panjang,i.Lebar,Coalesce(a.SheetSisa,0) as Sheet, ");
                sb.Append(" COALESCE(a.QtySisa,0) as QtyUnit,i.SatuanUnit,i.UnitPrice,COALESCE(a.QtySisa,0) * i.UnitPrice AS Amount, ");
                sb.Append(" w.WarehouseName,i.KodePallet,i.KodeMasuk,i.[Description],i.IsStock ");
                sb.Append(" from Inventory i    ");
                sb.Append(" LEFT JOIN    ");
                sb.Append(" (     ");
                sb.Append(" Select  (QtySisa) AS QtySisa,(SerialNumber) AS SerialNumber,  ");
                sb.Append(" (SheetSisa) AS  SheetSisa,(m.KodeWarehouse) AS KodeWarehouse,  ");
                sb.Append(" RANK() OVER (PARTITION BY SerialNumber,KodeWarehouse ORDER BY TglMutasi DESC) AS Ranking ");
                sb.Append(" from MutasiStok m  Where [TYPE]<>'MutasiWarehouse'   ");
                sb.Append(" and CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, TglMutasi)))<='" + Convert.ToDateTime(Periode, new System.Globalization.CultureInfo("id-ID")).ToString("yyyy-MM-dd") + "'");
                sb.Append(" ) a on a.SerialNumber = i.SerialNumber AND a.Ranking=1 ");
                sb.Append(" LEFT JOIN  Item b on i.ItemID = b.ItemId      ");
                sb.Append(" LEFT JOIN  Subgroup c on b.SubgroupId = c.SubgroupId     ");
                sb.Append(" LEFT JOIN  Groups d on c.GroupId = d.GroupId   ");
                sb.Append(" INNER JOIN (Select SerialNumber,KodeWarehouse,Pallet AS KodePallet from uvw_mutasi_stok  WHERE uvw_mutasi_stok.QtySisa>0) iw ON i.SerialNumber = iw.SerialNumber AND iw.KodeWarehouse=a.KodeWarehouse ");
                sb.Append(" LEFT JOIN Warehouse w ON iw.KodeWarehouse = w.KodeWarehouse  ");
                sb.Append(" ) T ");
                sb.Append(" WHERE IsStock=1  and QtyUnit>0  ");
            }
            else
            {
                sb.Append("Select * from ( ");
                sb.Append(" SELECT ");
                sb.Append(" i.SerialNumber,b.ItemId,b.ItemName,c.SubGroupId,c.SubGroupName,d.GroupId,d.GroupName,    ");
                sb.Append(" i.NoBundle,i.QtyPack,i.Panjang,i.Lebar,Coalesce(a.SheetSisa,0) as Sheet, ");
                sb.Append(" COALESCE(a.QtySisa,0) as QtyUnit,i.SatuanUnit,i.UnitPrice,COALESCE(a.QtySisa,0) * i.UnitPrice AS Amount, ");
                sb.Append(" w.WarehouseName,i.KodePallet,i.KodeMasuk,i.[Description],i.IsStock ");
                sb.Append(" from Inventory i    ");
                sb.Append(" LEFT JOIN    ");
                sb.Append(" (     ");
                sb.Append(" Select  (m.QtySisa) AS QtySisa,(SerialNumber) AS SerialNumber,  ");
                sb.Append(" (m.SheetSisa) AS  SheetSisa,(m.KodeWarehouse) AS KodeWarehouse,  ");
                sb.Append(" RANK() OVER (PARTITION BY SerialNumber,KodeWarehouse ORDER BY TglMutasi DESC) AS Ranking ");
                sb.Append(" from MutasiStok m  Where   ");
                sb.Append(" CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, TglMutasi)))<='" + Convert.ToDateTime(Periode, new System.Globalization.CultureInfo("id-ID")).ToString("yyyy-MM-dd") + "'");
                sb.Append(" And KodeWarehouse='" + Warehouse.KodeWarehouse + "'");
                sb.Append(" ) a on a.SerialNumber = i.SerialNumber  AND a.Ranking=1     ");
                sb.Append(" LEFT JOIN  Item b on i.ItemID = b.ItemId      ");
                sb.Append(" LEFT JOIN  Subgroup c on b.SubgroupId = c.SubgroupId     ");
                sb.Append(" LEFT JOIN  Groups d on c.GroupId = d.GroupId   ");
                sb.Append(" LEFT JOIN (Select SerialNumber,KodeWarehouse,Pallet AS KodePallet from uvw_mutasi_stok) iw ON i.SerialNumber = iw.SerialNumber  ");
                sb.Append(" INNER JOIN Warehouse w ON iw.KodeWarehouse = w.KodeWarehouse AND iw.KodeWarehouse=a.KodeWarehouse ");
                sb.Append(" ) T ");
                sb.Append(" WHERE IsStock=1 and QtyUnit>0  ");
            }

            if (!string.IsNullOrEmpty(NoLog))
                sb.AppendFormat(" AND SerialNumber like'persen{0}persen'", NoLog);
            if (!string.IsNullOrEmpty(KodeMasuk))
                sb.AppendFormat(" AND KodeMasuk like 'persen{0}persen'", KodeMasuk);
            if (!string.IsNullOrEmpty(Keterangan))
                sb.AppendFormat(" AND [Description] like 'persen{0}persen'", Keterangan);
            if (!string.IsNullOrEmpty(Pallet))
                sb.AppendFormat(" AND KodePallet like 'persen{0}persen'", Pallet);
            if (NoBundle > 0)
                sb.AppendFormat(" AND NoBundle ={0}", NoBundle);
            if (Panjang1 > 0)
                sb.AppendFormat(" AND Panjang >={0} AND Panjang <={1}", Panjang1, Panjang2);
            if (Lebar1 > 0)
                sb.AppendFormat(" AND Lebar >={0} AND Lebar <={1}", Lebar1, Lebar2);
            if (Tinggi1 > 0)
                sb.AppendFormat(" AND Sheet >={0} AND Sheet <={1}", Tinggi1, Tinggi2);
            if (Amount > 0)
                sb.AppendFormat(" AND Amount =persen{0}persen", Amount);
            if (Hpp > 0)
                sb.AppendFormat(" AND UnitPrice =persen{0}persen", Hpp);


            if (Items.Any(x => x.IsSelected)) sb.Append(" AND ItemId in (");
            foreach (var item in Items.Where(x => x.IsSelected))
                sb.AppendFormat("'{0}',", item.ItemId);
            if (Items.Any(x => x.IsSelected))
            {
                sb.Remove(sb.Length - 1, 1);
                sb.Append(")");
            }

            if (Groups.Any(x => x.IsSelected)) sb.Append(" AND GroupID in (");
            foreach (var group in Groups.Where(x => x.IsSelected))
                sb.AppendFormat("'{0}',", group.GroupID);
            if (Groups.Any(x => x.IsSelected))
            {
                sb.Remove(sb.Length - 1, 1);
                sb.Append(")");
            }

            if (SubGroups.Any(x => x.IsSelected)) sb.Append(" AND SubGroupID in (");
            foreach (var subGroup in SubGroups.Where(x => x.IsSelected))
                sb.AppendFormat("'{0}',", subGroup.SubGroupID);
            if (SubGroups.Any(x => x.IsSelected))
            {
                sb.Remove(sb.Length  - 1, 1);
                sb.Append(")");
            }

           sb.Append(" ORDER BY SubGroupID,ItemId  ");

            string warehouse = Warehouse == null ? "" : Warehouse.WarehouseName;
            var type = IsSummary ? "Summary" : "Detail";
            MyButton button = new MyButton(ReportUrl + "LaporanKartuStok.aspx?sql=" + HttpUtility.UrlEncode(sb.ToString()) + "&periode=" + Periode.Value.ToString("dd-MM-yyyy") + "&warehouse=" + warehouse + "&page=" + Navigation.MyNavigation.CurrentSource + "&type=" + type);
            button.ClickMe();
        }

    }
}
